package com.xzx.shop_front_api.controller;

import com.xzx.shop_front_api.entity.*;
import com.xzx.shop_front_api.entity.Collection;
import com.xzx.shop_front_api.mapper.MembersMapper;
import com.xzx.shop_front_api.service.*;
import com.xzx.shop_front_api.utils.JsonResult;
import com.xzx.shop_front_api.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.highlight.Highlight;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightField;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightParameters;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("api/goods")
public class GoodsController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ESGoods esGoods;
    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    @Autowired
    private SearchHistoryService searchHistoryService;
    @Autowired
    private SearchHistory searchHistory;
    @Autowired
    private CollectionService collectionService;
    @Autowired
    private Collection collection;

    @Autowired
    private CommentService commentService;
    @Autowired
    private MembersService membersService;
    @Autowired
    private MembersMapper membersMapper;

    @PostMapping("add")
    public JsonResult add(@RequestBody Goods goods) {
        int result = goodsService.addGoods(goods);
        if (result == 0) {
            JsonResult.failed("添加失败");
        }
        //同步到es
        esGoods.setId(goods.getId());
        esGoods.setGoodsName(goods.getGoodsName());
        esGoods.setFirstCateId(goods.getFirstCateId());
        esGoods.setSecondCateId(goods.getSecondCateId());
        esGoods.setThirdCateId(goods.getThirdCateId());
        esGoods.setSalesNumber(goods.getSalesNumber());
        esGoods.setSalePrice(goods.getSalePrice());
        esGoods.setMainImage(goods.getMainImage());
        elasticsearchOperations.save(esGoods);

        return JsonResult.success("添加成功",null);
    }

    @GetMapping("list")
    public JsonResult list(@RequestParam("cate_id") int cateId ,
                           @RequestParam("level") int level) {
        List<Goods> goodsList = goodsService.getGoodsByCateId(cateId, level);
        return JsonResult.success("获取成功",goodsList);
    }

    @GetMapping("search")
    public JsonResult search(@RequestParam("keyword") String keyword,
                             @RequestParam(value = "cate_id",defaultValue = ")") int cateId,
                             @RequestParam(value = "level",defaultValue = "level") int level,
                             @RequestParam(value = "order_by",defaultValue = "") String orderBy,
                             @RequestParam("member_id") int memberId
                             ) {
        //添加搜索历史
        //验证重复性
        SearchHistory result = searchHistoryService.getHistoryByMemberIdWord(memberId, keyword);
        if (result == null) {
            searchHistory.setWord(keyword);
            searchHistory.setMemberId(memberId);
            searchHistory.setCreatedTime(Tool.getCurrentTime());
            searchHistoryService.insertSearchHistory(searchHistory);
        }

        //添加热词
        String key = "shop:search_hot_words";
        stringRedisTemplate.opsForZSet().incrementScore(key,keyword,1.0);

        // 创建高亮配置
        HighlightField highlightField = new HighlightField("goods_name");
        HighlightParameters parameters = HighlightParameters.builder()
                .withPreTags("<em_word>")
                .withPostTags("</em_word>")
                .withFragmentSize(Integer.MAX_VALUE)
                .withNumberOfFragments(1)
                .build();


        Highlight highlight = new Highlight(parameters, List.of(highlightField));
        HighlightQuery highlightQuery = new HighlightQuery(highlight, ESNews.class);


        NativeQuery query = null;
        if(keyword != null && !keyword.isEmpty()) {
            query = NativeQuery.builder()
                    .withQuery(q -> q
                            .match(m -> m
                                    .field("goods_name")
                                    .query(keyword)
                            )
                    )
                    .withHighlightQuery(highlightQuery)
                    .build();
        } else {
            if (cateId !=0) {
                if (level == 1) {
                    System.out.println(cateId);
                        query = NativeQuery.builder()
                            .withQuery(q -> q
                                    .match(m -> m
                                            .field("first_cate_id")
                                            .query(cateId)
                                    )
                            )
                            .build();
                }
                if (level == 2) {
                        query = NativeQuery.builder()
                            .withQuery(q -> q
                                    .match(m -> m
                                            .field("second_cate_id")
                                            .query(cateId)
                                    )
                            )
                            .build();
                }

                if (level == 3) {
                        query = NativeQuery.builder()
                            .withQuery(q -> q
                                    .match(m -> m
                                            .field("third_cate_id")
                                            .query(cateId)
                                    )
                            )
                            .build();
                }
            }
        }
        SearchHits<ESGoods> searchHits = elasticsearchOperations.search(query, ESGoods.class);

        List<ESGoods> goodsList = new ArrayList<>();
        for (SearchHit<ESGoods> searchResult :searchHits.getSearchHits()) {
            List<String> arrGoodsName = searchResult.getHighlightFields().get("goodsName");
            esGoods.setId(Long.valueOf(Objects.requireNonNull(searchResult.getId())));
            ESGoods content = searchResult.getContent();
            esGoods.setGoodsName(arrGoodsName.get(0));
            esGoods.setFirstCateId(content.getFirstCateId());
            esGoods.setSecondCateId(content.getSecondCateId());
            esGoods.setThirdCateId(content.getThirdCateId());
            esGoods.setSalesNumber(content.getSalesNumber());
            esGoods.setSalePrice(content.getSalePrice());
            esGoods.setMainImage(content.getMainImage());
            goodsList.add(esGoods);
        }
        HashMap<String, Object> resultData = new HashMap<>();
        resultData.put("list", goodsList);
        resultData.put("total", searchHits.getTotalHits());

        return JsonResult.success("搜索成功",null);
    }

    //搜索历史关键词接口
    @GetMapping("search_history")
    public JsonResult searchHistory(@RequestParam("member_id") int memberId) {
        List<SearchHistory> historyList = searchHistoryService.getHistoryByMemberId(memberId);
        return JsonResult.success("查询成功",historyList);
    }

    //搜索热词列表接口
    @GetMapping("search_hots")
    public JsonResult searchHots() {
        String key = "shop:search_hot_words";
        Set<String> hotWordList = stringRedisTemplate.opsForZSet().reverseRange(key, 0, 1);
        return JsonResult.success("查询成功",hotWordList);
    }
    //商品详情接口
    @GetMapping("goods_details")
    public JsonResult goodsDetails(@RequestParam("id") int id) {
        Goods goodsInfo = goodsService.getGoodsById(id);
        return JsonResult.success("查询成功",goodsInfo);
    }

    //商品收藏/取消收藏
    @PostMapping("collect")
    public JsonResult collect(@RequestParam(value = "goods_id",defaultValue = "0") int goodsId,
                              @RequestParam(value = "member_id",defaultValue = "0") int memberId
                              ) {
        if (goodsId ==0 || memberId == 0) {
            return JsonResult.failed("商品id和会员id不能为空");
        }
        //添加/取消收藏操作
        Collection collectionInfo = collectionService.getCollectByMemberIdGoodsId(goodsId, memberId);
        if (collectionInfo == null) {
            collection.setGoodsId(goodsId);
            collection.setMemberId(memberId);
            collection.setCreatedTime(Tool.getCurrentTime());
            collectionService.insertCollection(collection);
        } else {
            //取消收藏
            int result = collectionService.deleteCollection(goodsId, memberId);
            if (result == 0) {
                return JsonResult.failed("操作失败");
            }
        }

        return JsonResult.success("ok",null);
    }

    //收藏状态查询接口
    @GetMapping("collect_status")
    public JsonResult collectStatus(@RequestParam(value = "goods_id",defaultValue = "0") int goodsId,
                                    @RequestParam(value = "member_id",defaultValue = "0") int memberId) {
        Collection collectionInfo = collectionService.getCollectByMemberIdGoodsId(goodsId, memberId);
        int collectStatus = 0;
        if (collectionInfo != null) {
            collectStatus =1;
        }
        return JsonResult.success("ok",collectStatus);
    }


    //评论查询接口
    @GetMapping("comment_list")
    public JsonResult commentList(@RequestParam(value = "goods_id",defaultValue = "0") int goodsId,
                                    @RequestParam(value = "page",defaultValue = "1") int page,
                                    @RequestParam(value = "limit",defaultValue = "5") int limit
                                    ) {
        List<Comment> commentList = commentService.getCommentByGoodsId(goodsId, page, limit);
        return JsonResult.success("ok",commentList);
    }
}
